package prototype.deep;

import java.io.*;

public class DeepPrototype implements Serializable,Cloneable {

    private String name;
    private DeepCloneableTarget target;

    public DeepPrototype() {
        super();
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        DeepPrototype deep = null;
        deep = (DeepPrototype) super.clone();
        deep.target = (DeepCloneableTarget) target.clone();
        return deep;
    }

    public Object deepClone() {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            // 序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            // 反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepPrototype copyObj = (DeepPrototype) ois.readObject();
            return copyObj;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();

            } catch (Exception e) {

            }
        }
        return null;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public DeepCloneableTarget getTarget() {
        return target;
    }

    public void setTarget(DeepCloneableTarget target) {
        this.target = target;
    }
}
